package cn.wolfcode.crm.web.controller;


import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.query.JsonResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    // 查询所有请求信息
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo<Role> pageResult = roleService.query(qo);
        model.addAttribute("result",pageResult);
        return "role/list";
    }

    // 添加新的信息
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            if (id != null) {
                roleService.delete(id);
                return new JsonResult(true,"删除成功");
            }
            }catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(true,"删除失败");
    }


    // 添加新的信息
    @RequestMapping("/input")
    public String input(Model model,Long id){
        model.addAttribute("permissions",permissionService.listAll());
        // 如果 id 不为空,携带该 id 对应的数据过 input 视图
        if (id != null) {
            model.addAttribute("role",roleService.get(id));
        }
        // 跳转到 input 视图
        return "role/input";
    }

    // 添加 或 修改 信息
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids){
        if (role.getId() != null) {
            // 如果 id 不为空,调用 修改方法
            roleService.update(role,ids);
        }else {
            // 如果 id 为空,调用保存方法
            roleService.save(role,ids);
        }
        return "redirect:/role/list.do";
    }
}
